package com.controller.activiti;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.FormService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.common.ActivitiUtils;
import com.dao.activiti.ActivitiMapper;

@Controller
@RequestMapping("/ActivitiManage")
public class ActivitiOprController {
	static final Logger logger = LoggerFactory.getLogger(ActivitiOprController.class);

	@Autowired
	ProcessEngine processEngine;

	@Autowired
	TaskService taskService;

	@Autowired
	HistoryService historyService;

	@Autowired
	RepositoryService repositoryService;

	@Autowired
	IdentityService identityService;

	@Autowired
	RuntimeService runtimeService;

	@Autowired
	FormService formService;

	@Autowired
	private ActivitiMapper activitiMapper;

	@RequestMapping(value = "/PendingTaskListJson", produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public String PendingTaskListJson(HttpServletRequest request) {
		try {
//			String assignee = request.getParameter("userid");
			String assignee = "chenxingbo";
//			TaskQuery taskQuery = taskService.createTaskQuery().taskAssignee(assignee);
//			List<Task> list = taskQuery.list();
//			List<TaskModel> taskList = new ArrayList<TaskModel>();
//			for (Task task : list) {
//
//			}
			List<HashMap<String, Object>> taskList = activitiMapper.selectModuleMap(assignee);
			String jsonString = JSON.toJSONString(taskList, SerializerFeature.WriteDateUseDateFormat);
			logger.info(jsonString);
			return jsonString;
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMessage", "" + e.getMessage());
			logger.error("errorMessage:{}", e.getMessage());
			return e.getMessage();
		}
	}

	@RequestMapping(value = "/getCurrentImg")
	public void getwfImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String taskId = request.getParameter("taskid");
		// 1. 获取到当前活动的ID
		Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
		ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId())
				.singleResult();
		BpmnModel bpmnModel = repositoryService.getBpmnModel(pi.getProcessDefinitionId());
		// 得到流程执行对象
		List<Execution> executions = runtimeService.createExecutionQuery().processInstanceId(pi.getId()).list();
		// 得到正在执行的Activity的Id
//		List<String> activityIds = new ArrayList<String>();
//		for (Execution exe : executions) {
//			List<String> ids = runtimeService.getActiveActivityIds(exe.getId());
//			activityIds.addAll(ids);
//		}
		// 高亮环节id集合
		List<String> highLightedActivitis = new ArrayList<String>();
		List<HistoricActivityInstance> highLightedActivitList = historyService.createHistoricActivityInstanceQuery()
				.processInstanceId(pi.getId()).list();
		for (HistoricActivityInstance tempActivity : highLightedActivitList) {
			String activityId = tempActivity.getActivityId();
			highLightedActivitis.add(activityId);
		}
		ProcessDefinitionEntity definitionEntity = (ProcessDefinitionEntity) repositoryService
				.getProcessDefinition(pi.getProcessDefinitionId());
		// 高亮线路id集合
		List<String> highLightedFlows = ActivitiUtils.getHighLightedFlows(definitionEntity, highLightedActivitList);
		ProcessDiagramGenerator pdg = processEngine.getProcessEngineConfiguration().getProcessDiagramGenerator();
		InputStream in = pdg.generateDiagram(bpmnModel, "png", highLightedActivitis, highLightedFlows, // Collections.<String>emptyList(),
				processEngine.getProcessEngineConfiguration().getActivityFontName(),
				processEngine.getProcessEngineConfiguration().getLabelFontName(), null, 1.0);
		response.setContentType("image/png");
		OutputStream stream;
		stream = response.getOutputStream();
		byte[] b = new byte[1024];
		int len;
		while ((len = in.read(b)) != -1) {
			stream.write(b, 0, len);
		}
		in.close();
		stream.flush();
		stream.close();
	}

	@RequestMapping(value = "/getWfImg")
	public void viewImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 从仓库中找需要展示的文件
		String deploymentId = request.getParameter("devid");
		List<String> names = repositoryService.getDeploymentResourceNames(deploymentId);
		String imageName = null;
		for (String name : names) {
			if (name.indexOf(".png") >= 0) {
				imageName = name;
			}
		}
		if (imageName != null) {
			InputStream in = repositoryService.getResourceAsStream(deploymentId, imageName);
			response.setContentType("image/png");
			OutputStream stream;
			stream = response.getOutputStream();
			byte[] b = new byte[1024];
			int len;
			while ((len = in.read(b)) != -1) {
				stream.write(b, 0, len);
			}
			in.close();
			stream.flush();
			stream.close();
		}
	}
}
